package com.pro.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pro.dao.BookMapper;
import com.pro.domain.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private CategoryService categoryService;
    @Override
    public IPage<Book> paging(Long categoryId,String order,Integer page, Integer rows) {

        Page<Book> p = new Page<Book>(page,rows);
        //组装查询和排序条件
        QueryWrapper<Book> queryWrapper = new QueryWrapper<Book>();
        //按类别，如果category，null，-1，就查所有类别
        if(categoryId!=null&&categoryId!=-1){
            queryWrapper.eq("category_id",categoryId);
        }
        //排序
        if(order!=null){
            if(order.equals("quantity")){//按数量
                queryWrapper.orderByDesc("evaluation_quantity");
            }else if(order.equals("score")){//按评分
                queryWrapper.orderByDesc("evaluation_score");
            }
        }
        //按条件查询
        IPage<Book> pageObject = bookMapper.selectPage(p, queryWrapper);
        return pageObject;
    }

    @Override
    public IPage<Book> paging2(HttpSession session,Long categoryId, String order, Integer page, Integer rows) {

        Page<Book> p = new Page<Book>(page,rows);
        //组装查询和排序条件
        QueryWrapper<Book> queryWrapper = new QueryWrapper<Book>();
        //按类别，如果category，null，-1，就查所有类别
//        if(categoryId!=null&&categoryId!=-1){
//            queryWrapper.eq("category_id",categoryId);
//        }
        //排序
        if(order!=null){
            if(order.equals("quantity")){//按数量
                queryWrapper.orderByDesc("evaluation_quantity");
            }else if(order.equals("score")){//按评分
                queryWrapper.orderByDesc("evaluation_score");
            }
        }
        List<Book> bookList = categoryService.selectMysave(session);
        if (bookList.size()==0){
            return null;
        }
        for (int i = 0; i < bookList.size(); i++) {
            queryWrapper.eq("book_id",bookList.get(i).getBookId());
            queryWrapper.or();
        }

        //按条件查询
        IPage<Book> pageObject = bookMapper.selectPage(p, queryWrapper);
        return pageObject;
    }

    @Override
    public Book getBookById(Long bookId) {
        Book book = bookMapper.selectById(bookId);
        return book;
    }

    /**
     * 更新图书评分，评价量
     */
    @Transactional //事务
    public void updateEvaluation() {
        bookMapper.updateEvaluation();
    }
}
